package com.tianji.promotion.utils;

import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.BooleanUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
public class RedisLock {

    private final String key;
    private final StringRedisTemplate redisTemplate;

    private boolean trylock(long leaseTime, TimeUnit unit){

        //获取线程名称
        String name = Thread.currentThread().getName();
        //获取锁
        Boolean setIfAbsent = redisTemplate.opsForValue().setIfAbsent(key, name, leaseTime, unit);
        //返回结果
        return BooleanUtils.isTrue(setIfAbsent);
    }

    //释放锁
    public void unlock(){
        redisTemplate.delete(key);
    }

}
